package org.wishwork.api.sign.verify;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.JSTService;
import org.wishwork.context.Context;
import org.wishwork.helper.JuShuiTanHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 签名验证
 * @author: WangYX
 * @create: 2022-04-01 17:37
 * @Version: 1.0.0
 **/

public class Verify {

    private static final Logger log = LoggerFactory.getLogger(JSTService.class);

    private Context context;

    public Verify(Context context) {
        this.context = context;
    }

    /**
     * 验证签名
     *
     * @param verify 验证签名请求体
     * @return
     */
    public boolean verify(VerifyRequest verify) {

        log.info("聚水潭授权回调参数：appKey-{},code-{},state-{},sign-{}", verify.getAppKey(), verify.getCode(), verify.getState(), verify.getSign());

        //验签
        Map<String, String> params = new HashMap<>();
        params.put("app_key", verify.getAppKey());
        params.put("code", verify.getCode());
        if (StrUtil.isNotBlank(verify.getState())) {
            params.put("state", verify.getSign());
        }
        //首先判断是否开启了签名验证
        if (context.properties().getSignature()) {
            //根据参数计算出签名
            String result = JuShuiTanHelper.signTopRequest(params, context.properties().getAppSecret(), JuShuiTanHelper.SIGN_METHOD_MD5);
            //用计算的签名和回调的签名进行比较
            return verify.getSign().equals(result);
        }
        return true;
    }


}
